package com.bird.web.controller.system.ts;

import cn.hutool.core.date.DateUtil;
import com.bird.common.annotation.Log;
import com.bird.common.constant.Constants;
import com.bird.common.enums.BusinessType;
import com.bird.common.utils.Assert;
import com.bird.common.utils.tkmybatis.TK;
import com.bird.framework.domain.Result;
import com.bird.framework.utils.SecurityUtils;
import com.bird.system.domain.bo.LoginUser;
import com.bird.system.domain.entity.TsPhoneDataEntity;
import com.bird.system.domain.params.TsPhoneDataQueryParam;
import com.bird.system.domain.params.TsPhoneDataUpdateParam;
import com.bird.system.domain.vo.TsPhoneDataListPcVO;
import com.bird.system.service.ITsGroupService;
import com.bird.system.service.ITsPhoneDataService;
import com.bird.web.controller.common.BaseController;
import com.bird.web.importRule.PhoneDataVerify;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.github.stupdit1t.excel.Column;
import com.github.stupdit1t.excel.ExcelUtils;
import com.github.stupdit1t.excel.callback.ParseSheetCallback;
import com.github.stupdit1t.excel.common.ImportRspInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;

/**
 * 数据Controller
 *
 * @author bird
 * @date 2020-09-23
 */
@Api(tags = "数据")
@RestController
@RequestMapping("/system/data")
public class TsPhoneDataController extends BaseController {

	@Autowired
	private ITsPhoneDataService tsPhoneDataService;

	@Autowired
	private ITsGroupService tsGroupService;

	@ApiOperation("查询数据列表")
	@PreAuthorize("@ss.hasPermi('system:data:list')")
	@GetMapping("/list")
	public Result<PageInfo<TsPhoneDataListPcVO>> list(TsPhoneDataQueryParam queryParams) {
		startPage();
		queryParams.setUserId(SecurityUtils.getLoginUser().getUserId());
		List<TsPhoneDataListPcVO> list = tsPhoneDataService.selectListPC(queryParams);
		return page(list);
	}

	@ApiOperation("查询下拉框")
	@GetMapping("/dropdown")
	public Result<List<TsPhoneDataEntity>> dropdown() {
		Long userId = SecurityUtils.getLoginUser().getUserId();
		List<TsPhoneDataEntity> data = tsPhoneDataService.selectList(
				TK.select(TsPhoneDataEntity.class).distinct().column("theName").where()
						.andEqualTo(TsPhoneDataEntity::getCreSb, userId)
						.end()
		);
		return ok(data);
	}

	@ApiOperation("获取数据详细信息")
	@PreAuthorize("@ss.hasPermi('system:data:query')")
	@GetMapping(value = "/{id}")
	public Result<TsPhoneDataEntity> info(@PathVariable("id") Long id) {
		return ok(tsPhoneDataService.selectById(id));
	}

	@ApiOperation("新增数据")
	@PreAuthorize("@ss.hasPermi('system:data:add')")
	@Log(title = "数据", businessType = BusinessType.INSERT)
	@PostMapping
	public Result<Long> add(@RequestBody TsPhoneDataUpdateParam updateParam) {
		return ok(tsPhoneDataService.insertPC(updateParam, SecurityUtils.getLoginUser().getUserId()));
	}

	@ApiOperation("修改数据")
	@PreAuthorize("@ss.hasPermi('system:data:edit')")
	@Log(title = "数据", businessType = BusinessType.UPDATE)
	@PutMapping
	public Result<Integer> edit(@RequestBody TsPhoneDataUpdateParam updateParam) {
		return ok(tsPhoneDataService.updateByIdPC(updateParam));
	}

	@ApiOperation("删除数据")
	@PreAuthorize("@ss.hasPermi('system:data:remove')")
	@Log(title = "数据", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
	public Result<Integer> remove(@PathVariable Long[] ids) {
		return ok(tsPhoneDataService.deleteByIds(ids));
	}

	@ApiOperation("删除数据组")
	@PreAuthorize("@ss.hasPermi('system:data:remove')")
	@Log(title = "数据", businessType = BusinessType.DELETE)
	@DeleteMapping("/group/{name}/{pwd}")
	public Result<Integer> remove(@PathVariable String name, @PathVariable String pwd) {
		LoginUser loginUser = SecurityUtils.getLoginUser();
		String password = loginUser.getPassword();
		Assert.isFalse(SecurityUtils.matchesPassword(pwd, password), "清除失败, 密码错误!");
		return ok(tsPhoneDataService.deleteByParams(TsPhoneDataEntity.builder().theName(name).build()));
	}

	@ApiOperation("手机数据导出")
	@Log(title = "手机数据导出", businessType = BusinessType.EXPORT)
	@GetMapping("/export")
	public void export(TsPhoneDataQueryParam queryParams) throws Exception {
		List<TsPhoneDataListPcVO> list = tsPhoneDataService.selectListPC(queryParams);
		ObjectMapper objectMapper = new ObjectMapper();
		String jsonData = objectMapper.writeValueAsString(list);
		List listJsonData = objectMapper.readValue(jsonData, List.class);
		String[] header = {"名字", "手机号", "创建人"};
		Column[] columns = {
				Column.field("theName").width(10),
				Column.field("phone").width(11),
				Column.field("creSb.name"),
		};
		ExcelUtils.ExportRules exportRules = ExcelUtils.ExportRules.simpleRule(columns, header);
		exportRules.title("手机号码数据");
		exportRules.autoNum(true);
		exportRules.sheetName("手机号码数据");
		Workbook workbook = ExcelUtils.createWorkbook(listJsonData, exportRules, true);
		export(workbook, "手机号数据" + DateUtil.date().toString(Constants.DatePattern.NORM_DATE_PATTERN) + ".xlsx");
	}

	@ApiOperation("模板下载")
	@GetMapping("/download")
	public void download() {
		String[] header = {"数据描述", "手机号"};
		Column[] columns = {
				Column.field("数据描述").width(10),
				Column.field("手机号").width(12),
		};
		ExcelUtils.ExportRules exportRules = ExcelUtils.ExportRules.simpleRule(columns, header);
		exportRules.sheetName("手机号码数据");
		Workbook workbook = ExcelUtils.createWorkbook(Collections.emptyList(), exportRules, true);
		export(workbook, "手机号数据导入模板.xlsx");
	}

	@ApiOperation("导入")
	@PreAuthorize("@ss.hasPermi('system:data:import')")
	@PostMapping(value = "/import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
	public Result importExcel(HttpServletResponse rsp, MultipartFile file) {
		try (
				InputStream inputStream = file.getInputStream();
		) {
			if (inputStream.available() == 0) {
				return no("请填充模板数据导入!");
			}
			Workbook workbook = WorkbookFactory.create(inputStream);
			Sheet sheetAt = workbook.getSheetAt(0);
			ImportRspInfo<TsPhoneDataEntity> result = ExcelUtils.parseSheet(TsPhoneDataEntity.class, PhoneDataVerify.getInstance(), sheetAt, 1, 0, new ParseSheetCallback<TsPhoneDataEntity>() {
				@Override
				public void callback(TsPhoneDataEntity tsPhoneDataEntity, int rowNum) throws Exception {
					tsPhoneDataEntity.setCreSb(SecurityUtils.getLoginUser().getUserId());
					// 随机测试
					//tsPhoneDataEntity.setPhone(RandomUtil.randomNumbers(11));
				}
			});
			workbook.close();
			if (result.isSuccess()) {
				// 解析成功
				List<TsPhoneDataEntity> list = result.getData();
				tsPhoneDataService.insertBatch(list);
				return ok("导入成功 " + result.getData().size() + "条!");
			} else {
				return no(result.getMessage());
			}
		} catch (Exception e) {
			e.printStackTrace();
			return no("导入未知异常");
		}
	}
}
